package com.yf.system.modules.points.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.base.api.api.dto.PagingReqDTO;
import com.yf.notify.enums.MsgTmpl;
import com.yf.system.modules.points.dto.UserPointsDTO;
import com.yf.system.modules.points.entity.UserPoints;
import com.yf.system.modules.points.mapper.UserPointsMapper;
import com.yf.system.modules.points.service.UserPointsService;
import com.yf.system.modules.user.dto.request.UserMsgReqDTO;
import com.yf.system.modules.user.entity.SysUser;
import com.yf.system.modules.user.service.SysUserService;
import com.yf.system.modules.user.service.UserMsgService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.LinkedHashMap;

/**
 * <p>
 * 积分日志业务实现类
 * </p>
 *
 * @author 聪明笨狗
 * @since 2021-02-20 09:09
 */
@Service
public class UserPointsServiceImpl extends ServiceImpl<UserPointsMapper, UserPoints> implements UserPointsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private UserMsgService userMsgService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void incr(String userId, int points, String refRemark, String refId) {


        // 积分重复性校验
        QueryWrapper<UserPoints> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(UserPoints::getUserId, userId)
                .eq(UserPoints::getRefId, refId);

        int count = this.count(wrapper);
        if(count >0 ){
            return;
        }


        // 查找用户并增加积分
        SysUser user = sysUserService.getById(userId);

        if (user.getPoints() == null) {
            user.setPoints(points);
        } else {
            user.setPoints(user.getPoints() + points);
        }
        sysUserService.updateById(user);

        // 保存日志
        UserPoints record = new UserPoints();
        record.setPoints(points);
        record.setRefId(refId);
        record.setRefRemark(refRemark);
        record.setUserId(userId);
        this.save(record);

        // 发消息
        UserMsgReqDTO dto = new UserMsgReqDTO();
        dto.setTmplId(MsgTmpl.POINTS_GET);
        dto.setUseIm(true);
        dto.setUseSms(true);
        dto.setUseEmail(true);
        dto.setUserIds(Arrays.asList(new String[]{userId}));

        LinkedHashMap<String,String> params = new LinkedHashMap<>();
        params.put("title", refRemark);
        params.put("num", String.valueOf(points));
        dto.setParams(params);
        userMsgService.sendMsg(dto);
    }

    @Override
    public IPage<UserPointsDTO> paging(PagingReqDTO<UserPointsDTO> reqDTO) {

        // 创建分页对象
        Page query = reqDTO.toPage();


        //查询条件
        QueryWrapper<UserPoints> wrapper = new QueryWrapper<>();

        // 请求参数
        UserPointsDTO params = reqDTO.getParams();

        if(params != null){
            if(!StringUtils.isBlank(params.getUserId())){
                wrapper.lambda().eq(UserPoints::getUserId, params.getUserId());
            }

            if(!StringUtils.isBlank(params.getRefRemark())){
                wrapper.lambda().like(UserPoints::getRefRemark, params.getRefRemark());
            }
        }

        // 排序倒序
        wrapper.lambda().orderByDesc(UserPoints::getCreateTime);

        //获得数据
        IPage<UserPoints> page = this.page(query, wrapper);
        //转换结果
        IPage<UserPointsDTO> pageData = JSON.parseObject(JSON.toJSONString(page),
                new TypeReference<Page<UserPointsDTO>>() {
        });
        return pageData;
    }


}
